class CartItem {
  final int? id;
  final String? title;
  final String? cover;
  final num? salePrice;
  final num? marketPrice;
  final String? thirdCategoryName;
  final String? unit;
  int quantity;

  CartItem({
    this.id,
    this.title,
    this.cover,
    this.salePrice,
    this.marketPrice,
    this.thirdCategoryName,
    this.unit,
    this.quantity = 1,
  });

  // 从JSON创建CartItem
  factory CartItem.fromJson(Map<String, dynamic> json) {
    return CartItem(
      id: json['id'],
      title: json['title'],
      cover: json['cover'],
      salePrice: json['salePrice'],
      marketPrice: json['marketPrice'],
      thirdCategoryName: json['thirdCategoryName'],
      unit: json['unit'],
      quantity: json['quantity'] ?? 1,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'cover': cover,
      'salePrice': salePrice,
      'marketPrice': marketPrice,
      'thirdCategoryName': thirdCategoryName,
      'unit': unit,
      'quantity': quantity,
    };
  }

  // 从ProductInfoBean创建CartItem
  factory CartItem.fromProduct(dynamic product) {
    return CartItem(
      id: product.id,
      title: product.title,
      cover: product.cover,
      salePrice: product.salePrice,
      marketPrice: product.marketPrice,
      thirdCategoryName: product.thirdCategoryName,
      unit: product.unit,
      quantity: 1,
    );
  }

  // 计算总价
  double get totalPrice {
    return ((salePrice ?? 0) / 100.0) * quantity;
  }

  // 复制并修改数量
  CartItem copyWith({int? quantity}) {
    return CartItem(
      id: id,
      title: title,
      cover: cover,
      salePrice: salePrice,
      marketPrice: marketPrice,
      thirdCategoryName: thirdCategoryName,
      unit: unit,
      quantity: quantity ?? this.quantity,
    );
  }
}